import actionTypes from './constant';
import { loginRequest } from '../../services';   //登录的网络请求
import { message } from 'antd';


//登录成功
const loginSuccess = (userInfo) => {
    return {
        type: actionTypes.LOGIN_SUCCESS,
        payLoad: {
            ...userInfo,
            isLogin: true
        }
    }
}

//登录失败处理函数
const loginFailed = () => {
    //清除本地记录
    window.sessionStorage.removeItem('authToken');
    window.sessionStorage.removeItem('user_id');
    window.sessionStorage.removeItem('user_password');
    window.sessionStorage.removeItem('role');
    return {
        type: actionTypes.LOGIN_FAILED
    }
}

//退出登录
export const logout = () => {
    window.sessionStorage.removeItem('authToken');
    window.sessionStorage.removeItem('user_id');
    window.sessionStorage.removeItem('user_password');
    window.sessionStorage.removeItem('role');


    return {
        type: actionTypes.LOGOUT
    }
}

//登录
export const login = (userLoginInfo) => {
    console.log("进入登陆处理函数");

    return dispatch => {
        loginRequest(userLoginInfo)
        .then( res => {
            //返回状态码为200，表示成功
            console.log(res);
            if(res.status === 200)
            {
                console.log(userLoginInfo);
                //本地化存储
                const authToken = res.token;
                window.sessionStorage.setItem('authToken', authToken);
                window.sessionStorage.setItem('user_id', userLoginInfo.user_id);
                window.sessionStorage.setItem('user_password', userLoginInfo.user_password);
                window.sessionStorage.setItem('role', userLoginInfo.role);
            
                // dispatch(loginSuccess({
                //     ...userLoginInfo
                // }))
                dispatch(loginSuccess({
                    ...res.userInfo
                }))
            }
            else
            {
                message.error("用户名或密码填写错误，登录失败！")
                dispatch(loginFailed()); //登录失败
            }
        })
        
    }

}